<?php
namespace Auntie\Controller;
use Think\Controller;
class WxController extends Controller {
	
	public static $wx;   //缓存微信对象
	public static $wx_openid;  //缓存微信对象
	public static $usertable;  //用户表
	
	public function __construct($options){
		self::$usertable=M('weixin_auntie_user');
		
		$options['appid']=C('BB_APPID_auntie');
		$options['secret']=C('BB_SECRET_auntie');
		$options['token']=C('BB_TOKEN');
		self::$wx=new \bb\Wechat($options);
		
		//判断验证模式
		if(IS_GET){
			self::$wx->valid();
		}else{
			if(!self::$wx->valid()){die('no access!!!');}
			$data=self::$wx->request();
			//==调试信息====================================
			/*
			foreach($data as $k=>$v){
				$str=$str.$k."=>".$v.'  ';
			}
			file_put_contents('调试log.txt','收到请求:'.date('Y-m-d H:i:s').PHP_EOL.'通知信息:'.$str.PHP_EOL.PHP_EOL.PHP_EOL,FILE_APPEND);
			*/
			//==调试信息====================================
			self::$wx_openid=$data['fromusername'];
			//==和公众号有交互的时候更新用户信息=====================================================
			if($data['msgtype']!='event' || ($data['event']!='LOCATION' &&  $data['event']!='TEMPLATESENDJOBFINISH')){ //不要在更新坐标和发送模板消息的时候更新用户
				$user=self::$usertable->where(array('openid'=>self::$wx_openid))->find();
				if($user){
					$userdata=self::$wx->user(self::$wx_openid);
					$userdata['id']=$user['id'];
					self::$usertable->save($userdata);
					unset($user,$userdata);
				}else{
					$userdata=self::$wx->user(self::$wx_openid);
					self::$usertable->add($userdata);
					unset($user,$userdata);
				}
			}
			//=====================================================================
			switch($data['msgtype']){
				case 'text':
					$this->checkKeyword($data['content'],$data);
					break;
				case $data['msgtype']=='image' || $data['msgtype']=='voice' || $data['msgtype']=='video' || $data['msgtype']=='shortvideo' || $data['msgtype']=='location' || $data['msgtype']=='link':
					$this->checkKeyMedia($data);
					break;
				case 'event':
					$this->checkEvent($data);
					break;
				default:
					self::$wx->response("本系统暂时无法识别您的指令！",'text');
			}
		}
	}
	//默认页面
	public function index(){
		
	}
	//文本消息
	public function checkKeyword($Keyword,$request){
		$m=M('weixin_keyword');
		$news=M('weixin_news');
		$data=$m->where(array('keyword'=>$Keyword,'wx_id'=>3))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}else{
			self::$wx->response("no",'text');
		}
	}
		
	//事件消息
	public function checkEvent($data){
		switch($data['event']){
			//关注
			case 'subscribe':
				if($data['eventkey']){
					//扫码关注
					$this->checksmsubscribe($data['eventkey'],$data['ticket']);
				}else{
					//关注
					$this->checksubscribe();
				}
				break;
			//取消关注
			case 'unsubscribe':
				$this->checkunsubscribe();
				break;
			//关注后扫码
			case 'SCAN':
				$this->checkscan($data['eventkey'],$data['ticket']);
				break;
			//上报用户地理位置
			case 'LOCATION':
				$this->checklocation($data['latitude'],$data['longitude'],$data['precision']);
				break;
			//自定义菜单事件命令
			case 'CLICK':
				$this->checkCLICK($data['eventkey']);
				break;
			//自定义菜单事件打开网页
			case 'VIEW':
				$this->checkVIEW($data['eventkey']);
				break;
			default:
				self::$wx->response("本系统暂时无法识别你的事件 ！",'text');
		}
	}
	//关注公众号
	public function checksubscribe(){
		$m=self::$usertable;
		$user=$m->where(array('openid'=>self::$wx_openid))->find();
		if($user){
			$userdata=self::$wx->user(self::$wx_openid);
			$userdata['id']=$user['id'];
			$m->save($userdata);
		}else{
			$userdata=self::$wx->user(self::$wx_openid);
			$m->add($userdata);
		}
		//==获得需要 获动结束就取消===============================================================
//		$array[0]['title']='迎中秋，庆国庆 ▍猜_boss☞赢月饼&电影票&红酒&红包';
//		$array[0]['description']='文中大咖都是中国商界的顶级精英；双节来了，各位大佬一定动作频频！！“我要洗衣” app随时全面上线之前，决定做个小小活动抛砖引玉！哈哈~作为一个爱学习，爱创新的互联网O2O干洗团队，决定吸取各位大咖优点，以此来造福广大用户！';
//		$array[0]['picurl']='http://wx.iwantwash.com/Public/h/img/cboss.png';
//		$array[0]['url']='http://mp.weixin.qq.com/s?__biz=MzAxOTE2Mjk3OQ==&mid=208319680&idx=1&sn=997c2fac71af589add7596c6678cf65c&scene=23&srcid=09197TFjxSX73NcgXQkJilEh#rd';
//		$array[1]['title']='疯狂数钱赢红包！敢不敢来挑战？';
//		$array[1]['description']='一阳指？点穴手？听说数钱会上瘾？点钞赢微信现金红包，不服来战!';
//		$array[1]['picurl']='http://wx.iwantwash.com/Public/h/img/fx.jpg';
//		$array[1]['url']='http://wx.iwantwash.com/H/sq/index/id/1';
//		self::$wx->sendMsg(self::$wx_openid,$array,'news');
		//================================================================
		$keym=M('weixin_keyword');
		$data=$keym->where(array('keyword'=>"首次关注"))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}else{
			self::$wx->response("no",'text');
		}
		
		self::$wx->response("感谢您的关注！".$data['id'],'text');
	}
	
	//扫描2微码关注公众号
	public function checksmsubscribe($eventkey,$ticket){
		//获取2维码的参数=============
		if($eventkey){
			$eventkey=substr($eventkey,8);
			$shopid='shop'.$eventkey;
			$array[0]['Title']='我是社区管家，去录入我的信息';
			$array[0]['Description']='';
			$array[0]['PicUrl']='http://wx.tingzan88.com/Public/auntie/img/sequ.jpg';
			$array[0]['Url']='http://wx.tingzan88.com/Auntie/index/addauntie/shopid/'.$shopid;
			self::$wx->response($array,'news');
		}
		//========================
		$m=self::$usertable;
		$userdata=self::$wx->user(self::$wx_openid);
		$m->add($userdata);
		$keym=M('weixin_keyword');
		$data=$keym->where(array('keyword'=>"首次关注"))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}else{
			self::$wx->response("?",'text');
		}
	}
	
	//关注过扫码
	public function checkscan($eventkey,$ticket){
		//获取2维码的参数=============
		if($eventkey){
			$shopid='shop'.$eventkey;
			$array[0]['Title']='我是社区管家，去录入我的信息';
			$array[0]['Description']='';
			$array[0]['PicUrl']='http://wx.tingzan88.com/Public/auntie/img/sequ.jpg';
			$array[0]['Url']='http://wx.tingzan88.com/Auntie/index/addauntie/shopid/'.$shopid;
			self::$wx->response($array,'news');
		}
		//========================
		$m=self::$usertable;
		$user=$m->where(array('openid'=>self::$wx_openid))->find();
		if($user){
			$userdata=self::$wx->user(self::$wx_openid);
			$userdata['id']=$user['id'];
			$m->save($userdata);
		}else{
			$userdata=self::$wx->user(self::$wx_openid);
			$m->add($userdata);
		}
	}
	
	//自定义菜单事件命令
	public function checkCLICK($eventkey){
		$m=M('weixin_keyword');
		$news=M('weixin_news');
		$message=M('weixin_message');
		$data=$m->where(array('keyword'=>$eventkey))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}else{
			if($eventkey=='getorder'){
				//获取附件没有抢的订单
				$auntie=M('bb_auntie')->select();
				if($auntie){
					$zb = S('zb'.self::$wx_openid);
					$lat=$zb['latitude'];
					$lon=$zb['longitude'];
					$squares = returnSquarePoint($lon, $lat, C('BB_NEAR_QM'));  //最后一个参数是查找附进多少千米的订单
				 	$info_sql = "select * from `bb_order` where status='0' and gps_lat<>0 and gps_lat>{$squares['right-bottom']['lat']} and gps_lat<{$squares['left-top']['lat']} and gps_lon>{$squares['left-top']['lng']} and gps_lon<{$squares['right-bottom']['lng']} ORDER BY `addstamp` DESC LIMIT 1"; 
					$order=M('bb_order')->query($info_sql);
					if($order){
						//推送给阿姨端消息
						$tp=new \bb\template();
						$array=array(
							'name'=>$order[0]['name'],
							'phone'=>$order[0]['phone'],
							'time'=>$order[0]['prckup_dtm'],
							'orderid'=>$order[0]['orderid'],
							'neirong'=>'快去抢单把'
						);
						foreach ($auntie as $k => $v){
							if($v['openid']==self::$wx_openid){
								$templatedata=$tp->enddata('put_order',$v['openid'],$array);	//组合模板数据
								self::$wx->sendTemplate($templatedata);	//发送模板
							}
						}
					}else{
						self::$wx->response("您的附近没有待抢的订单！",'text');
					}
				}
				//==============================
			}
			
			self::$wx->response("no",'text');
		}
		
	}
	
	//自定义菜单事件打开网页
	public function checkVIEW($eventkey){
		//微信会打开这个网址$eventkey
	}
	
	//用户地理位置
	public function checklocation($latitude,$longitude,$precision){
		$m=self::$usertable;
		$user=$m->where(array('openid'=>self::$wx_openid))->find();
		if($user){
			$url = "http://api.map.baidu.com/geoconv/v1/?coords=".$longitude.",".$latitude."&from=1&to=5&ak=".C('BB_AK');
	 		$re = get_curl($url);
			$zb = json_decode($re,true);
			if($zb['status']==0){
				$userdata['longitude']=$zb['result']['0']['x'];
				$userdata['latitude']=$zb['result']['0']['y'];
				$userdata['id']=$user['id'];
				$m->save($userdata);		//更新用户位置坐标。
				
				$wz['gps_lon']=$zb['result']['0']['x'];
				$wz['gps_lat']=$zb['result']['0']['y'];
				M('bb_auntie')->where(array('openid'=>self::$wx_openid))->save($wz);
				S('zb'.self::$wx_openid,$userdata);
				//self::$wx->response('坐标更新了！'.$wz['gps_lat'],'text');
			}else{
				//self::$wx->response($zb['status'],'text');
				//self::$wx->sendMsg('oY8X0s9aYANqYI3ETXPnlKYcDS4o',$zb['status'],'text');
			}
		}
	}
	
	//==多媒体资料处理=======================================================
	public function checkKeyMedia($data){
		$message=M('weixin_message');
		switch($data['msgtype']){
			//用户发来照片
			case 'image':
				$path=self::$wx->download_medis($data['mediaid']);	//下载图片到本地
				$data['content']=$path;
				break;
			//用户发来语音
			case 'voice':
				$data['content']=$data['recongnition'];				//语音识别结果
				break;
			//用户发来视频
			case 'video':
				//暂不处理
				break;
			//用户发来小视频
			case 'shortvideo':
				//暂不处理
				break;
			//用户发来地理位置
			case 'location':
				//暂不处理
				break;
			//用户发来链接
			case 'link':
				//暂不处理
				break;
			default:
				self::$wx->response("本系统暂时无法识别您的指令！",'text');
		}
        $re=$message->add($data);
		if($re){
			self::$wx->response("no",'text');
		}else{
			self::$wx->response('没有收到您发送的数据，请重试！','text');
		}
	}
	//取消关注公众号
	public function checkunsubscribe(){
		$m=self::$usertable;
		$user=$m->where(array('openid'=>self::$wx_openid))->find();
		$m->delete($user['id']);		//删除取消关注的会员
	}
	
	//遍历微信图文回复数据
	public function newsbl($data){
		foreach ($data as $k => $v) {
			$img=$this->getPic($v['img']);
			$array[$k]['Title']=$v['title'];
			$array[$k]['Description']=$v['info'];
			$array[$k]['PicUrl']=$img['imgurl'];
			$array[$k]['Url']=htmlspecialchars_decode($v['url']);
		}
		return $array;
	}
	//获取单张图片地址
	public function getPic($id){
		$m=M('weixin_upload_img');
		$map['id']=$id;
		$list=$m->where($map)->find();
		if($list){
			$list['imgurl']=C('BB_URL')."/Upload/".$list['savepath'].$list['savename'];
		}
		return $list?$list:"";
	}
}